package com.carb.context;

import com.carb.constant.JwtConstant;

import java.util.Map;

/**
 * 用户上下文
 */
public class UserContext {

    // userMap = {userId=1, role=管理员}
    private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public static void setUser(Map<String, Object> userMap){
        threadLocal.set(userMap);
    }

    public static Long getUserId(){
        Map<String, Object> userMap = threadLocal.get();
        if (userMap == null) {
            // 若没有用户信息，则返回-1
            return -1L;
        }
        return (Long) userMap.get(JwtConstant.USER_ID);
    }

    public static String getUserRole(){
        Map<String, Object> userMap = threadLocal.get();
        return (String) userMap.get(JwtConstant.ROLE);
    }

    public static void removeUser(){
        threadLocal.remove();
    }

}
